<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useInfiniteScroll } from '@vueuse/core';
import ArticleItem from '@/components/article-item.vue';
import ArticleCarouselItem from '@/components/article-carousel-item.vue';
import { selectPageArticleFront, selectRecommend } from '@/api/article';
import type { Article } from '@/api/article/types.ts';
import Message from '@/components/message';
import ArticleSkeleton from '@/views/home/components/ArticleSkeleton.vue';
import EmptyState from '@/views/home/components/EmptyState.vue';
import ArticleCarousel from '@/views/home/components/ArticleCarousel.vue';

interface QueryParams {
  pageNo: number;
  pageSize: number;
  status: number;
  category: string;
}

const route = useRoute();
const loading = ref(false);
const hasMore = ref(true);
const initialLoading = ref(true);
const loadTrigger = ref<HTMLElement | null>(null);

// 从地址栏获取分类id
const categoryId = computed(() => {
  const id = route.query.id as string;
  return id && route.fullPath.includes('category') ? id : '0';
});

// 查询参数
const params = ref<QueryParams>({
  pageNo: 1,
  pageSize: 5,
  status: 1,
  category: categoryId.value
});

// 文章列表数据
const articleList = ref<Article[]>([]);
const recommendList = ref<Article[]>([]);

// 查询文章列表
const selectArticlePage = async () => {
  try {
    loading.value = true;
    const result = await selectPageArticleFront(params.value);
    const newArticles = result.data;

    if (params.value.pageNo === 1) {
      articleList.value = newArticles;
    } else {
      articleList.value = [...articleList.value, ...newArticles];
    }

    hasMore.value = newArticles.length === params.value.pageSize;
  } catch (error) {
    Message.error('获取文章列表失败');
    console.error('获取文章列表失败:', error);
  } finally {
    loading.value = false;
    initialLoading.value = false;
  }
};

// 查询推荐列表
const selectArticleRecommend = async () => {
  try {
    const result = await selectRecommend();
    recommendList.value = result.data;
  } catch (error) {
    Message.error('获取推荐列表失败');
    console.error('获取推荐列表失败:', error);
  }
};

// 自动加载更多
const loadMore = async () => {
  if (loading.value || !hasMore.value) return;
  params.value.pageNo++;
  await selectArticlePage();
};

// 设置无限滚动
useInfiniteScroll(
  loadTrigger,
  async () => {
    await loadMore();
  },
  {
    distance: 10,
    throttle: 500
  }
);

// 刷新列表
const refreshList = () => {
  params.value.pageNo = 1;
  selectArticlePage();
};

onMounted(() => {
  Promise.all([selectArticlePage(), selectArticleRecommend()]);
});
</script>

<template>
  <div class="home-container">
    <template v-if="initialLoading">
      <ArticleSkeleton v-for="n in 4" :key="n" />
    </template>

    <template v-else>
      <!-- 轮播图部分 -->
      <div class="list-carousel box-radius" v-if="recommendList.length">
        <ArticleCarousel :item-count="recommendList.length">
          <div
            v-for="item in recommendList"
            :key="item.id"
            class="carousel-item"
          >
            <ArticleCarouselItem :item="item" />
          </div>
        </ArticleCarousel>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && articleList.length === 0" class="empty-state">
        <EmptyState>
          <template #extra>
            <button class="refresh-btn" @click="refreshList">
              刷新试试
            </button>
          </template>
        </EmptyState>
      </div>

      <!-- 文章列表 -->
      <template v-else>
        <ArticleItem :list="articleList" />

        <!-- 加载状态指示器 -->
        <div
          ref="loadTrigger"
          class="load-more-trigger"
        >
          <div v-if="hasMore" class="loading-indicator">
            <div class="bottom-dots">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="text">{{ loading ? '加载中...' : '上拉加载更多' }}</span>
            </div>
          </div>
          <div v-else class="bottom-dots">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="text">已经到底啦</span>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>

<style scoped lang="less">
.home-container {
  width: 100%;

  .list-carousel {
    width: 100%;
    height: 232px;
    margin-bottom: 24px;
    overflow: hidden;

    .carousel-item {
      flex-shrink: 0;
      width: 100%;
      height: 100%;
    }
  }

  .load-more-trigger {
    padding: 20px 0;
    text-align: center;
  }

  .loading-indicator {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40px;
  }

  .refresh-btn {
    margin-top: 16px;
    padding: 8px 16px;
    border: none;
    border-radius: 20px;
    background: #EFF6FF;  // 浅蓝色背景
    color: #3B82F6;      // 主蓝色
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: #DBEAFE;  // 稍深的蓝色背景
      transform: translateY(-1px);
    }
  }
}

.bottom-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;

  .dot {
    width: 4px;
    height: 4px;
    margin: 0 3px;
    background: #9CA3AF;  // 灰色圆点
    border-radius: 50%;
    opacity: 0.5;

    &:nth-child(1) { animation: fade 1s infinite 0s; }
    &:nth-child(2) { animation: fade 1s infinite 0.2s; }
    &:nth-child(3) { animation: fade 1s infinite 0.4s; }
  }

  .text {
    margin-left: 10px;
    font-size: 14px;
    color: #4B5563;  // 深灰色文字
  }
}

@keyframes fade {
  0%, 100% { opacity: 0.5; }
  50% { opacity: 0.2; }
}
</style>
